package com.dick.base.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dick.base.aop.SmartQuery;
import com.dick.base.exception.UsernameDuplicatedException;
import com.dick.base.mapper.BaseUserMapper;
import com.dick.base.model.BaseUser;
import com.dick.base.parameter.UserParameter;
import com.dick.base.session.dto.PasswordParameter;
import com.dick.base.session.util.SessionUtil;
import com.dick.base.util.IdUtil;
import com.dick.base.util.PageInfo;
import com.dick.base.util.PasswordUtil;
import com.dick.base.util.SmartQueryUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户管理service
 */
@Service
public class UserService {

    @Autowired
    private BaseUserMapper baseUserMapper;

    /**
     * 用户分页查询
     * @param user
     * @param pageInfo
     * @return
     */
    @SmartQuery(clazz = BaseUser.class, likeFields = "username")
    public Page<BaseUser> userPage(BaseUser user, PageInfo pageInfo) {
        return baseUserMapper.selectPage(SmartQueryUtil.getPage(), SmartQueryUtil.getQueryWrapper());
    }

    /**
     * 新增用户
     * @param userParameter 用户信息
     */
    @Transactional
    public void userAdd(UserParameter userParameter) {
        BaseUser baseUser = baseUserMapper.selectOne(
                new QueryWrapper<BaseUser>().eq("username", userParameter.getUsername()));
        if (baseUser == null) {
            BaseUser user = new BaseUser();
            user.setId(IdUtil.nextId());
            user.setUsername(userParameter.getUsername());
            user.setSalt(PasswordUtil.generatePasswordSalt());
            user.setPassword(PasswordUtil.generatePassword(userParameter.getPassword(), user.getSalt()));
            baseUserMapper.insert(user);
        } else {
            throw new UsernameDuplicatedException();
        }
    }

    /**
     * 重置用户密码
     * @param userParameter
     */
    public void passwordReset(UserParameter userParameter) {
        BaseUser baseUser = baseUserMapper.selectOne(
                new QueryWrapper<BaseUser>().eq("username", userParameter.getUsername()));
        if (baseUser != null) {
            BaseUser user = new BaseUser();
            user.setId(baseUser.getId());
            user.setSalt(PasswordUtil.generatePasswordSalt());
            user.setPassword(PasswordUtil.generatePassword(userParameter.getPassword(), user.getSalt()));
            baseUserMapper.updateById(user);
        }
    }

}
